import React, { useState, useEffect, useRef } from 'react'
import './style.less'
import { Button, Space, Popconfirm, Form, Flex } from 'antd'
import { HsAdminTablePage, HsAdminInput, HsAdminForm, HsAdminSpin } from '@hs-admin/base-components'
import { PERMISSIONS, getItem, usePage, message } from '@hs-admin/utils'
import { reqSetBannerIntro, reqGetBannerIntro } from '@/api/assetMaintain/basicsData'
import EditModal from './edit'
import { handleButtonShow } from '@/utils/tools'
import {
  moveDownDataDomain,
  moveUpDataDomain,
  reqDataDomainList,
  reqDeleteDataDomain,
  reqPublishDataDomain,
  reqRevokeDataDomain
} from '@/api/assetMaintain/industry/domain'
import MoveSort from '@/components/global/NewMoveSort'

const DataTheme: React.FC = () => {
  const permissions = getItem(PERMISSIONS) || []
  const [describe, setdescribe] = useState('')
  const [form] = Form.useForm()
  const formItemOptions: any[] = [
    {
      label: '领域名称',
      name: 'keywords',
      component: 'Input',
      FormItemColProps: {
        span: 6
      }
    },
    {
      label: '状态',
      name: 'status',
      component: 'Select',
      componentProps: {
        options: [
          { label: '上架', value: 'published' },
          { label: '下架', value: 'draft' }
        ],
        onChange: handleSearch
      },
      FormItemColProps: {
        span: 6
      }
    },
    {
      slot: 'submit',
      FormItemColProps: {
        span: 12
      },
      FormItemProps: {
        labelCol: { span: 0 },
        wrapperCol: { span: 24 }
      }
    }
  ]
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callList)
  const [data, setData] = useState<any[]>([])

  const moveUp = (record: any) => {
    moveUpDataDomain({ id: record.id }).then(() => {
      message.success('上移成功')
      callList()
    })
  }
  const moveDown = (record: any) => {
    moveDownDataDomain({ id: record.id }).then(() => {
      message.success('下移成功')
      callList()
    })
  }
  const columns = [
    {
      title: '移动',
      width: 100,
      render: (_: any, record: any, index: number) => (
        <MoveSort pagination={pagination} record={record} index={index} data={data} moveUp={moveUp} moveDown={moveDown} />
      )
    },
    {
      title: '领域名称',
      dataIndex: 'name'
    },
    {
      title: '领域描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '最新维护人',
      dataIndex: 'owner.name'
    },
    {
      title: '最新维护时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_: any, record: any) => {
        const name = record.status === 'draft' ? '下架' : '上架'
        return <span>{name}</span>
      }
    },
    {
      title: '操作',
      key: 'actions',
      fixed: 'right',
      render: (_: any, record: any) => actionCompute(record)
    }
  ]
  const actionCompute = (record: any) => (
    <Space size="small">
      {permissions.includes('datashop.data_domain.update') && (
        <Button type="link" size="small" onClick={() => edit(record)}>
          编辑
        </Button>
      )}
      {permissions.includes('datashop.data_domain.update') && record.status === 'published' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            await reqRevokeDataDomain({ id: record.id })
            message.success('下架成功')
            resetPage()
          }}>
          下架
        </Button>
      )}
      {permissions.includes('datashop.data_domain.update') && record.status === 'draft' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            await reqPublishDataDomain({ status: 1, id: record.id })
            message.success('上架成功')
            resetPage()
          }}>
          上架
        </Button>
      )}
      {permissions.includes('datashop.data_domain.delete') && record.status === 'draft' && (
        <Popconfirm
          title="警告"
          description="确定删除该项吗?"
          onConfirm={async () => {
            await reqDeleteDataDomain({ id: record.id })
            message.success('删除成功')
            resetPage()
          }}>
          <Button type="link" size="small">
            删除
          </Button>
        </Popconfirm>
      )}
    </Space>
  )
  const editRef = useRef<any>(null)
  const [loading, setloading] = useState(true)

  // 搜索
  async function handleSearch() {
    resetPage()
  }
  // 列表查询事件
  async function callList() {
    setloading(true)
    const fieldsValues = form.getFieldsValue()
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keywords: fieldsValues.keywords,
      status: fieldsValues.status
    }
    const res = await reqDataDomainList(params)
    const tableData = res.items ?? []
    setData(tableData)
    setloading(false)
    return res
  }
  // 重置
  const reset = () => {
    form.resetFields()
    resetPage()
  }
  const save = async () => {
    const res = await reqSetBannerIntro({ obj_id: 2, intro: describe })
    if (res.code === 200) {
      message.success('保存成功!')
    }
  }
  const getDesc = async () => {
    const res = await reqGetBannerIntro(2)
    if (res.code === 200) {
      setdescribe(res.data.intro || '--')
    }
  }
  const addTheme = () => {
    editRef.current.showModal()
  }
  const edit = (record: any) => {
    editRef.current.showModal(record)
  }

  useEffect(() => {
    getDesc()
  }, [])

  return (
    <div className="basicsTheme">
      {loading && <HsAdminSpin />}
      <Flex justify="space-between">
        产业数仓定义
        <Button type="primary" onClick={save}>
          保存
        </Button>
      </Flex>
      <HsAdminInput
        value={describe}
        TextArea
        placeholder="请输入"
        onChange={(e: { target: { value: React.SetStateAction<string> } }) => setdescribe(e.target.value)}
        className="mt-2"
      />
      <br />
      <br />
      <HsAdminForm form={form} formItemOptions={formItemOptions}>
        <div slot="submit">
          <Flex align="center" justify="space-between">
            <Space className="ml-2">
              <Button onClick={reset}>重置</Button>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
            </Space>
            {handleButtonShow('datashop.data_domain.create') && (
              <Button type="primary" onClick={addTheme}>
                新增领域
              </Button>
            )}
          </Flex>
        </div>
      </HsAdminForm>
      <HsAdminTablePage columns={columns} rowKey="id" dataSource={data} pagination={pagination} size="small"></HsAdminTablePage>
      <EditModal ref={editRef} finish={resetPage} />
    </div>
  )
}

export default DataTheme
